// goodsdetail.js
var shihan = require('../../common/fetch')
var config = require('../../common/config')
var app = getApp()
var winScale = 750 / app.data.deviceInfo.windowWidth
var num = 0,
  num2 = 0,
  num3 = 0,
  num4 = 0;
var selectattrvalue = ''
var pages, token = ''
var addflag = true
var clickflag = true
var goodstimer, goodstimer2;
var usercid
var sceneres = {}
var range, range1, range2, range3;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    poptype: '',
    selectnum: 1,
    goodsinfo: {},
    minutesimg: '',
    plusimg: '3',
    priceflag: true,
    selectimgindex: '0',
    toast_flag: false,
    foldflag: false,
    showLoading: true,
    maskVisual: 'hidden',
    inhibitInput: '',
    buttonflag: true,
    mask_flag: false,
    mask_flag: false,
    hideimg: false,
    refresh: true,
    dialogflag: true,
    farenodes: [],
    cardFlag: false,
    share_money: '',
    painting: {},
    shareImage: '',
    currentTab: 0,
    toView: 'ladder_0',
    description: [],
    scroll_top: [],
    tab_show: false,
    res_navbar: ['商品', '评价', '详情', '推荐'],
    defaults: 'https://img-oss.shihanbainian.com/shihan2/index/defaults.png'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    var that = this
    var res = wx.getSystemInfoSync()
    pages = getCurrentPages();
    if (pages.length >= 2) {
      var prevPage = pages[pages.length - 2];
      prevPage.setData({
        refresh: true,
        promotefresh: false
      })
    }
    this.setData({
      winWidth: res.windowWidth,
      winHeight: res.windowHeight,
      currenscrollH: (res.windowHeight) * winScale - 98,
    })
    range = 794 / (750 / this.data.winWidth)
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-in-out',
    });
    this.animation = animation;

    this.animation.translateY(range).step();
    this.setData({
      showModalStatus: false,
      animationData: this.animation.export()
    });

    range1 = 1090 / winScale;
    var animation1 = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    this.animation1 = animation1;

    range2 = this.data.winHeight;
    var animation2 = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    this.animation2 = animation2;

    range3 = 1160 / winScale;
    var animation3 = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    this.animation3 = animation3;

    var animation4 = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    this.animation4 = animation4;

    if (options.scene) {
      var scene1 = decodeURIComponent(options.scene).split('&'); //gid=2&pid=123
      if (scene1 && scene1.length > 0) {
        for (var i = 0; i < scene1.length; i++) {
          var str = scene1[i].split('=')
          if (str[0] == 'gid') {
            this.setData({
              goodsid: str[1]
            })
          }
          if (str[0] == 'pid') {
            sceneres['partner_id'] = str[1]
          } else if (str[0] == 'cid') {
            sceneres['cid'] = str[1]
            config.partner_id = ''
            config.reg_partner = 0
          }
        }
      }
    } else {
      var paramStr;
      if (options.cid) {
        sceneres['cid'] = options.cid
      } else if (options.pid) {
        sceneres['partner_id'] = options.pid
      } else if (options.fansid) {
        sceneres['partner_id'] = options.fansid
      } else if (options.partner_id) {
        sceneres['partner_id'] = options.partner_id
      }

      this.setData({
        goodsid: options.goodsid || '',
        category: options.category || ''
      })
    }
    console.log(sceneres)
    app.wechatSwitch().then(function(wechat_switch) { //是否打开微信授权开关
      app.commonLogin(sceneres, wechat_switch)
    })
  },

   /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this
    that.setData({
      usertoken: wx.getStorageSync('token'),
    })
    if (that.data.refresh) {
      that.loadgoodsdetail()
      wx.removeStorageSync('invoicekey')
    }
  },
  getFields: function () {
    var that = this, query = wx.createSelectorQuery();
    query.selectAll('.ladder').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      // console.log(res[0])
      that.setData({
        scroll_top: [
          {
            top: 0,
            height: res[0][0].height
          },
          {
            top: res[0][0].height,
            height: res[0][1].height
          },
          {
            top: res[0][0].height + res[0][1].height,
            height: res[0][2].height
          },
          {
            top: res[0][0].height + res[0][1].height + res[0][2].height - 200,
            height: res[0][3].height
          }
        ]
      })
      // console.log(that.data.scroll_top)
    })
  },
  onResNavbarTap: function (e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      toView: 'ladder_' + index,
      currentTab: index
    })
  },
  productteamview: function() { //product_team_view  product_team
    var that = this
    shihan.sendRequest(config.product_team + that.data.goodsid + '/1-10.html', 'GET', {})
      .then(function(response) {
        if (response.data.code == 0) {
          that.setData({
            groupinfo: response.data.data
          })
          if (response.data.data.sh_team_list.length > 0) {
            clearInterval(goodstimer2);
            goodstimer2 = setInterval(function() {
              response.data.data.sh_team_list.forEach(function(el, index) {
                var newgoodstime = {}
                newgoodstime['sh_id'] = el.sh_id
                newgoodstime['sh_end_time'] = el.sh_end_at
                that.timeCalculation(newgoodstime)
              })
            }, 1000);
          }
        }
      }, function(error) {
        console.log(error);
      });
  },
  timeCalculation: function(staretime) { //sh_create_at:"2017-08-28 16:23:26" 秒杀时间计算
    var that = this
    var time1 = new Date().getTime();
    var time2 = new Date(staretime.sh_end_time.replace(/-/g, '/'));

    if (time2 - time1 > 0) { //正在进行中
      var micro_second = time2 - time1;

      var time = micro_second / 1000;
      // 小时位
      var hour = Math.floor(time / 3600);
      hour = hour <= 9 ? '0' + hour : hour;
      // 分钟位
      var minute = Math.floor(time % 3600 / 60);
      minute = minute <= 9 ? '0' + minute : minute;
      // 秒数
      var second = Math.floor(time % 3600 % 60);
      second = second <= 9 ? '0' + second : second;
      that.data.groupinfo.sh_team_list.forEach(function(el, index) {
        if (staretime.sh_id == el.sh_id) {
          el.sh_last_time = hour + ':' + minute + ':' + second
          el.secondflag = true
          that.setData({
            groupinfo: that.data.groupinfo
          })
        }
      })
    } else {
      that.data.groupinfo.sh_team_list.forEach(function(el, index) {
        if (staretime.sh_id == el.sh_id) {
          el.secondflag = false
          el.sh_last_time = '00:00:00'
          that.setData({
            groupinfo: that.data.groupinfo
          })
        }
      })
    }
  },
  openvideo: function() {
    if (this.data.goodsinfo.sh_video) {
      wx.navigateTo({
        url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(this.data.goodsinfo.sh_video) + '&name='
      })
    }
  },
  grouprule: function(e) {
    var url = e.currentTarget.dataset.url
    if (url&&url.indexOf('https://') == 0) {
      wx.navigateTo({
        url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(url)
      })
    }
  },
  moregroup: function() {
    this.animation1.translateY(-range1).step();
    this.setData({
      mask_flag: true,
      animationData1: this.animation1.export()
    })
  },
  closegroup: function() {
    this.animation1.translateY(range1).step();
    this.setData({
      mask_flag: false,
      animationData1: this.animation1.export()
    })
  },
  openshare: function(e) {
    var that = this
    this.setData({
      sharetype: e.currentTarget.dataset.type || '',
      sharekinds: e.currentTarget.dataset.sharetype || '' //sharetype
    })
    if (!this.data.sharetype) {
      this.closegroup()
      this.setData({
        shareteamid: e.currentTarget.dataset.teamid || ''
      })
    }
    this.animation2.translateY(-range2).step();
    this.setData({
      animationData2: this.animation2.export()
    })
  },
  closeshare: function() {
    this.animation2.translateY(range2).step();
    this.setData({
      refresh: true,
      animationData2: this.animation2.export()
    })
  },
  openshareimg: function() {
    var that = this;
    wx.showLoading({
      title: '绘制中',
      mask: true
    })
    if (that.data.sharetype) {
      that.setData({
        painting: {
          width: 750,
          height: 1334,
          clear: true,
          views: [
            {
              type: 'image',
              url: 'https://img-oss.shihanbainian.com/upload_dev/images/b/2/3/b23e8f54e6ffb22ebb9705521cbc2470.jpg',
              top: 0,
              left: 0,
              width: 750,
              height: 1334
            },
            {
              type: 'image',
              url: that.data.share_good_img,
              top: 60,
              left: 40,
              width: 670,
              height: 670
            },
            {
              type: 'image',
              url: 'https://img-oss.shihanbainian.com/upload_dev/images/c/1/e/c1e897cd54f1e0e69157fc47e5351d36.png',
              top: 60,
              left: 40,
              width: 670,
              height: 12
            },
            {
              type: 'image',
              url: that.data.goodsinfo.sh_qrcode || 'https://img-oss.shihanbainian.com/shihan2/index/defaults.png',
              top: 983,
              left: 100,
              width: 250,
              height: 250
            },
            {
              type: 'text',
              content: that.data.share_good_name,
              fontSize: 40,
              color: '#222',
              textAlign: 'left',
              top: 770,
              left: 96,
              width: 558,
              MaxLineNumber: 1,
              breakWord: true,
              bolder: true
            },
            {
              type: 'text',
              content: that.data.share_good_subname,
              fontSize: 28,
              color: '#999',
              textAlign: 'left',
              top: 840,
              left: 96,
              width: 558,
              lineHeight: 42,
              breakWord: true,
              MaxLineNumber: 2
            },
            {
              type: 'text',
              line: 1,
              margin: 10,
              content: '￥' + that.data.share_good_show_price,
              fontSize: 32,
              color: '#cc363c',
              textAlign: 'left',
              top: 1037,
              left: 393,
              bolder: true
            },
            {
              type: 'text',
              content: '￥' + that.data.share_good_line_price,
              fontSize: 28,
              color: '#999',
              textAlign: 'left',
              top: 1042,
              left: 630.659375,
              textDecoration: 'line-through'
            },
            {
              type: 'text',
              content: '扫描或长按小程序码查看详情',
              fontSize: 28,
              color: '#222',
              textAlign: 'left',
              top: 1108,
              left: 392,
              lineHeight: 42,
              MaxLineNumber: 2,
              breakWord: true,
              width: 250
            }
          ]
        }
      })
    } else {
      shihan.sendRequest(config.product_team_view + that.data.shareteamid + '.html', 'GET', {})
        .then(function(response) {
          if (response.data.code == 0) {
            that.setData({
              groupshareinfo: response.data.data,
              painting: {
                width: 750,
                height: 1126,
                clear: true,
                views: [
                  {
                    type: 'image',
                    url: 'https://img-oss.shihanbainian.com/upload_dev/images/6/6/9/669cccc81ec823e50d356887eadf8790.jpg',
                    top: 0,
                    left: 0,
                    width: 750,
                    height: 1126
                  },
                  {
                    type: 'image',
                    url: that.data.share_good_img,
                    top: 0,
                    left: 0,
                    width: 750,
                    height: 750
                  },
                  {
                    type: 'image',
                    url: 'https://img-oss.shihanbainian.com/upload_dev/images/f/5/a/f5a276c8ebbca95583d0e682aa246c66.png',
                    top: 0,
                    left: 30,
                    width: 130,
                    height: 138
                  },
                  {
                    type: 'image',
                    url: that.data.goodsinfo.sh_headimgurl,
                    top: 706,
                    left: 30,
                    width: 90,
                    height: 90,
                    borderRadius: 45
                  },
                  {
                    type: 'image',
                    url: 'https://img-oss.shihanbainian.com/upload_dev/images/c/2/a/c2ab344bb67143209b9f0b012b8307b7.png',
                    top: 666,
                    left: 0,
                    width: 750,
                    height: 136
                  },
                  {
                    type: 'image',
                    url: response.data.data.sh_share_data&&response.data.data.sh_share_data.sh_qrcode || 'https://img-oss.shihanbainian.com/shihan2/index/defaults.png',
                    top: 790,
                    left: 480,
                    width: 240,
                    height: 240
                  }, 
                  {
                    type: 'image',
                    url: 'https://img-oss.shihanbainian.com/upload_dev/images/f/b/0/fb0f60a5434ace69cf2316a817913b4d.png',
                    top: 1050,
                    left: 30,
                    width: 100,
                    height: 40
                  },
                  {
                    type: 'text',
                    content: response.data.data.sh_nick_name,
                    fontSize: 32,
                    color: '#444',
                    textAlign: 'left',
                    top: 750,
                    left: 142
                  },
                  {
                    type: 'text',
                    content: response.data.data.sh_share_data.sh_title,
                    fontSize: 32,
                    color: '#444',
                    textAlign: 'left',
                    top: 825,
                    left: 30,
                    width: 410,
                    lineHeight: 46,
                    breakWord: true,
                    MaxLineNumber: 2
                  },
                  {
                    type: 'text',
                    content: '快来拼团和我一起享受优惠~',
                    fontSize: 28,
                    color: '#999',
                    textAlign: 'left',
                    top: 930,
                    left: 30
                  },
                  {
                    type: 'text',
                    line: 1,
                    margin: 10,
                    content: '￥' + response.data.data.sh_product.sh_show_price,
                    fontSize: 36,
                    color: '#cc363c',
                    textAlign: 'left',
                    top: 1050,
                    left: 138,
                    bolder: true
                  },
                  {
                    type: 'text',
                    content: '￥' + response.data.data.sh_product.sh_line_price,
                    fontSize: 32,
                    color: '#999',
                    textAlign: 'left',
                    top: 1056,
                    left: 316,
                    textDecoration: 'line-through'
                  },
                  {
                    type: 'text',
                    content: '扫描或长按二维码',
                    fontSize: 28,
                    color: '#666',
                    textAlign: 'left',
                    top: 1064,
                    left: 486
                  }
                ]
              }
            })
          }
        }, function(error) {
          console.log(error);
        });
    }
  },
  eventGetImage: function (event) {
    // console.log(event)
    const { tempFilePath, errMsg } = event.detail;
    if (errMsg === 'canvasdrawer:ok') {
      this.setData({
        shareImage: tempFilePath
      })
    }
    this.previewImage(this.data.shareImage);
  },
  previewImage: function (url) {
    var that = this, imgarr = [];
    imgarr.push(url)
    wx.hideLoading()
    wx.previewImage({
      urls: imgarr,
      success: function () {
        that.closeshare();
      }
    })
  },
  loadgoodsdetail: function() {
    var that = this
    shihan.sendRequest(config.goods_detail + that.data.goodsid + '.html', 'GET', {})
      .then(function(response) {
        if (response.data.code == 0) {
          //sh_product_type 商品类型 0普通商品 1秒杀商品 2团购商品 9其他活动商品
          if (response.data.data.sh_promotion_start_at && response.data.data.sh_promotion_end_at) {
            var newgoodstime = {}
            if (response.data.data.sh_product_type == 1) {//秒杀商品
              newgoodstime['goodstype'] = "second";
            } else if (response.data.data.sh_product_type == 2) {//团购商品
              newgoodstime['goodstype'] = "group";
            }
            newgoodstime['sh_start_time'] = response.data.data.sh_promotion_start_at
            // newgoodstime['sh_start_time'] = "2018-11-26 13:33:00";
            newgoodstime['sh_end_time'] = response.data.data.sh_promotion_end_at
            clearInterval(goodstimer);
            goodstimer = setInterval(function() {
              // that.dateformat();
              shihan.dateformat.call(that, newgoodstime);
            }, 1000);
          }
          response.data.data.selectattrstock = response.data.data.sh_all_stock;
          response.data.data.selectattrcommission = response.data.data.sh_partner_commission;
          if (response.data.data.sh_is_favorite == 0) {
            that.setData({
              collectionflag: false
            })
          } else {
            that.setData({
              collectionflag: true
            })
          }
          if (response.data.data.sh_label) {
            var iconpos = response.data.data.sh_label;
            iconpos['posa'] = iconpos.sh_location.split('_')[0];
            iconpos['posb'] = iconpos.sh_location.split('_')[1];
          }

          for (var i = 0; i < response.data.data.sh_products.length; i++) {
            if (response.data.data.sh_products[i].sh_label.sh_location) {
              var pos = response.data.data.sh_products[i].sh_label
              pos['posa'] = pos.sh_location.split('_')[0];
              pos['posb'] = pos.sh_location.split('_')[1];
            }
          }
          if (response.data.data.sh_salesrules) {
            for (var j = 0; j < response.data.data.sh_salesrules.length; j++) {
              response.data.data.sh_salesrules[j].selectfalg = false
              response.data.data.sh_salesrules[j].clickflag = true
            }
          }
          var bigarr = response.data.data.sh_attributes;
          for (var i = 0; i < bigarr.length; i++) {
            for (var j = 0; j < bigarr[i].sh_options.length; j++) {
              bigarr[i].selectattrid = ''
              bigarr[i].sh_options[j].active = false
              bigarr[i].sh_options[j].num = 1
            }
          }
          if (response.data.data.sh_remind_no_partner_arr && response.data.data.sh_remind_no_partner_arr.sh_content) {
            var str, str1, str2;
            var str = response.data.data.sh_remind_no_partner_arr.sh_content;
            var price = response.data.data.sh_remind_no_partner_arr.sh_price;
            var name = response.data.data.sh_remind_no_partner_arr.sh_wechat_num;

            if (price&&price.indexOf(str)) {
              str1 = str.split(price)
              that.data.farenodes.push(str1[0])
              that.data.farenodes.push(price)
            }
            if (name&&name.indexOf(str1[1])) {
              str2 = str1[1].split(name)
              that.data.farenodes.push(str2[0])
              that.data.farenodes.push(name)
              that.data.farenodes.push(str2[1])
            }

            that.setData({
              farenodes: that.data.farenodes
            })
          }
          
          if (response.data.data.sh_description&&response.data.data.sh_description.indexOf('<img')>0) {
            response.data.data.sh_description = response.data.data.sh_description.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;" ')
          }
          that.setData({
            showLoading: false,
            itemID: that.data.goodsid,
            shopnum: response.data.args.cart_num,
            itemName: response.data.data.sh_name,
            itemPrice: response.data.data.sh_price,
            itemCategory: that.data.category || '',
            itemID: that.data.goodsid,
            collectionid: that.data.goodsid,
            goodsinfo: response.data.data,
            buyproductid: that.data.goodsid,
            share_good_name: response.data.data.sh_name,
            share_good_subname: response.data.data.sh_subname,
            share_good_show_price: response.data.data.sh_show_price,
            share_good_line_price: response.data.data.sh_line_price,
            share_good_img: response.data.data.sh_galleries[0] || '',
            share_money: response.data.data.sh_partner_commission,
            thumbnail: response.data.data.sh_galleries[0] || '',
            selectattrmoney: response.data.data.sh_show_price
          })
          wx.reportAnalytics('page_product_detail', {
            product_id: that.data.goodsid,
            product_name: response.data.data.sh_name
          })
          
          if (response.data.data.sh_product_type == 2) {//团购商品
            that.productteamview();
          }
          // if (bigarr.length == 1) {
          that.setdisabled()
          // }
          if (response.data.data.sh_enabled_share == 0) {
            wx.hideShareMenu()
          }
          setTimeout(function(){
            that.getFields();
          },800)
        } else {
          wx.showModal({
            title: "提示",
            content: response.data.msg,
            confirmText: "确认",
            confirmColor: "#c40000",
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                if (pages.length == 1) {
                  wx.switchTab({
                    url: '/pages/home/home',
                  })
                } else {
                  wx.navigateBack({})
                }
              }
            }
          })
        }
      }, function(error) {
        console.log(error);
      });
    // console.log(that.data);
  },
  jumpadvert: function(e) { //广告位跳转
    app.AdSkipper(e)
  },
  openprefer: function() {
    if (this.data.goodsinfo.sh_product_type == 1) {//秒杀商品
      wx.navigateTo({
        url: '/pages/secondactivity/secondactivity',
      })
    }
  },
  pickupSalesrule: function(e) { //领取优惠券pick_up_salesrule
    var that = this
    var num = e.currentTarget.dataset.num
    var index = e.currentTarget.dataset.index

    if (that.data.goodsinfo.sh_salesrules[index].clickflag) {
      that.data.goodsinfo.sh_salesrules[index].clickflag = false
      shihan.sendRequest(config.pick_up_salesrule, 'POST', {
          'coupon_code': num
        })
        .then(function(response) {
          if (response.data.code == 0) {
            shihan.showToast.call(that, '领取优惠券成功！');
          } else if (response.data.code == 1101) {
            app.commonNoLogin()
          } else if (response.data.code == 20002) {
            shihan.showToast.call(that, response.data.msg);
            that.data.goodsinfo.sh_salesrules[index].clickflag = false
          } else {
            that.data.goodsinfo.sh_salesrules[index].clickflag = true
          }
          that.data.goodsinfo.sh_salesrules[index].selectfalg = true
          that.setData({
            goodsinfo: that.data.goodsinfo
          })
        }, function(error) {
          console.log(error);
          that.data.goodsinfo.sh_salesrules[index].clickflag = true
          that.setData({
            goodsinfo: that.data.goodsinfo
          })
        });
    }
  },
  //打开选择SKU弹窗
  openskuselect: function(e) {
    var that = this, drawerflag = true, 
      bigarr = that.data.goodsinfo.sh_attributes,
      token = wx.getStorageSync('token');
    if (token) {
      var timestatus = e.currentTarget.dataset.timestatus || '';
      that.setData({
        buymode: e.currentTarget.dataset.typebuy,
        buyteamid: e.currentTarget.dataset.teamid || ''
      })
      if (timestatus == 1 || timestatus == '') {
        if (!that.data.mask_flag) {
          that.closegroup()
          
          that.setData({
            poptype: e.currentTarget.dataset.type
          })

          that.setdisabled()
          that.checkselectsku();
        
          that.animation.translateY(-range).step();
          that.setData({
            mask_flag: true,
            animationData: that.animation.export()
          });
        } else {
          for (var i = 0; i < bigarr.length; i++) {
            if (bigarr[i].selectattrid == '') {
              drawerflag = false;
              shihan.showToast.call(that, '请选择' + bigarr[i].sh_label);
              break
            }
          }
          if (drawerflag) {
            if (that.data.buymode == 'indirectbuy') {
              shihan.sendRequest(config.add_to_cart, 'POST', {
                product_id: that.data.goodsinfo.selectattrallid,
                qty: that.data.selectnum
              })
                .then(function (response) {
                  if (response.data.code == 0) {
                    wx.reportAnalytics('click_add_cart', {
                      product_id: that.data.itemID,
                      product_name: that.data.itemName,
                      product_price: that.data.itemPrice,
                      product_category: that.data.itemCategory
                    })
                    // that.setData({
                    //   ball_active: 'active'
                    // })
                    // clearTimeout(ball);
                    // var ball = setTimeout(function(){
                    //   that.createAnimation(16, 128);
                    // }, 1)
                    that.setData({
                      shopnum: response.data.args.cart_num
                    });
                    shihan.showToast.call(that, '加入购物车成功');
                  } else if (response.data.code == 1101) { //用户未登录
                    app.commonNoLogin()
                  } else if (response.data.code == 1112) { //用户冻结
                    that.animation.translateY(range).step();
                    that.setData({
                      mask_flag: false,
                      animationData: that.animation.export()
                    });
                  } else {
                    shihan.showToast.call(that, response.data.msg);
                  }
                })
            } else {
              var buydata = {}
              buydata["buy_product"] = JSON.parse('{"' + that.data.goodsinfo.selectattrallid + '"' + ':' + that.data.selectnum + '}')
              if (that.data.buymode == 'groupbuy') {
                buydata["is_group_buy"] = '1'
                buydata["team_id"] = that.data.buyteamid
              } else if (that.data.buymode == "originbuy") {
                buydata["is_original_price"] = '1'
              }
              shihan.sendRequest(config.confirm_order, 'POST', buydata)
                .then(function (response) {
                  if (response.data.code == 0) {
                    that.animation.translateY(range).step();
                    that.setData({
                      mask_flag: false,
                      animationData: that.animation.export()
                    });
                    if (that.data.buymode == 'groupbuy') {
                      wx.navigateTo({
                        url: '/pages/firmorder/firmorder?product_id=' + that.data.goodsinfo.selectattrallid + '&number=' + that.data.selectnum + '&buytype=directbuy&groupbuy=1&originbuy=0&need=1&teamid=' + that.data.buyteamid,
                      })
                    } else if (that.data.buymode == 'originbuy') {
                      wx.navigateTo({
                        url: '/pages/firmorder/firmorder?product_id=' + that.data.goodsinfo.selectattrallid + '&number=' + that.data.selectnum + '&buytype=directbuy&groupbuy=0&originbuy=1&need=1',
                      })
                    } else {
                      wx.navigateTo({
                        url: '/pages/firmorder/firmorder?product_id=' + that.data.goodsinfo.selectattrallid + '&number=' + that.data.selectnum + '&buytype=directbuy&groupbuy=0&originbuy=0&need=1',
                      })
                    }
                  } else if (response.data.code == 1101) { //用户未登录
                    app.commonNoLogin()
                  } else if (response.data.code == 1112) { //用户冻结
                    that.animation.translateY(range).step();
                    that.setData({
                      mask_flag: false,
                      animationData: that.animation.export()
                    });
                  } else {
                    shihan.showToast.call(that, response.data.msg);
                  }
                }, function (error) {
                  console.log(error);
                });
            }
          }
        }
      } else if (timestatus == 0) {
        shihan.showToast.call(that, '该团已结束');
      }
    } else {
      app.commonNoLogin()
    }
  },
  setDelayTime: function (sec) {
    return new Promise((resolve, reject) => {
      setTimeout(() => { resolve() }, sec)
    });
  },
  // 创建动画
  createAnimation: function (ballX, ballY) {
    let that = this,
      bottomX = 120,
      bottomY = that.data.winHeight - 40,
      animationX = that.flyX(bottomX, ballX),      // 创建小球水平动画
      animationY = that.flyY(bottomY, ballY);			 // 创建小球垂直动画

    
    that.setData({
      ballX: ballX,
      ballY: ballY,
      showBall: true
    });
    setTimeout(function(){
      that.setData({
        showBall: false
      });
    },650)
    that.setDelayTime(100).then(() => {
      // 100ms延时,  确保小球已经显示
      that.setData({
        animationX: animationX.export(),
        animationY: animationY.export()
      });
      // 400ms延时, 即小球的抛物线时长
      return that.setDelayTime(700);
    }).then(() => {
      that.setData({
        showBall: false,
        animationX: this.flyX(0, 0, 0).export(),
        animationY: this.flyY(0, 0, 0).export()
      });
    })
  },
	// 水平动画
	flyX: function (bottomX, ballX, duration) {
    let animation = wx.createAnimation({
      duration: duration || 700,
      timingFunction: 'linear',
    })
    animation.translateX(bottomX - ballX).step();
    return animation;
  },
	// 垂直动画
  flyY: function (bottomY, ballY, duration) {
    let animation = wx.createAnimation({
      duration: duration || 700,
      timingFunction: 'ease-in',
    })
    animation.translateY(bottomY - ballY).step();
    return animation;
  },
  //关闭选择SKU弹窗
  closeMask: function(e) {
    this.animation.translateY(range).step();
    this.setData({
      mask_flag: false,
      animationData: this.animation.export()
    });
  },
  //底部弹窗促销和服务
  openPopup: function(e) {
    this.animation.translateY(-range).step();
    this.setData({
      mask_flag: true,
      animationData: this.animation.export(),
      promotiontype: e.currentTarget.dataset.promotiontype || '',
      poptype: e.currentTarget.dataset.type || ''
    });
  },
  backhome: function() {
    wx.switchTab({
      url: '/pages/home/home'
    });
  },
  // 滚动计算滚动条距离
  onScroll: function(ev) {
    var that = this, scrollTop = ev.detail.scrollTop;
    this.setData({
      backhomeheight: scrollTop > 200 ? 226 : 118,
      backToTop: scrollTop > 200 ? true : false,
      tab_show: scrollTop>0?true:false
    }) 
    that.data.scroll_top.forEach(function (el, index) {
      if (Math.abs(el.top - scrollTop)<100) {
        that.setData({
          currentTab: index
        });
      } 
    })
  },
  // 返回顶部
  onBackToTop: function() {
    this.setData({
      backToTop: false,
      scrollTop: 0,
      backhomeheight: 118
    })
  },
  goshoppingcart: function() {
    var that = this, token = wx.getStorageSync('token');
    if (token) {
      shihan.sendRequest(config.get_cart_list, 'POST', {})
        .then(function(response) {
          if (response.data.code == 0) {
            wx.switchTab({
              url: '/pages/shopping/shopping',
            })
          } else if (response.data.code == 1101) {
            app.commonNoLogin()
          } else {
            shihan.showToast.call(that, response.data.msg);
          }
        }, function(error) {});
    } else {
      app.commonNoLogin()
    }
  },
  selectsku: function(e) {
    var that = this
    var big = e.currentTarget.dataset.a
    var small = e.currentTarget.dataset.b
    var bigarr = this.data.goodsinfo.sh_attributes
    var activeitem = this.data.goodsinfo.sh_attributes[big]
    var numflag = false
    //点击时加上选中效果，并且判断该属性库存是否大于0 
    if (e.currentTarget.dataset.num > 0 && bigarr.length > 1) {
      // 如果属性没有选中
      if (activeitem.sh_options[small].active == false) {
        for (var i = 0; i < bigarr[big].sh_options.length; i++) {
          activeitem.sh_options[i].active = false
        }
        activeitem.sh_options[small].active = true
        bigarr[big].selectattr = activeitem.sh_options[small].sh_alias_name
        bigarr[big].selectattrid = activeitem.sh_options[small].sh_option_id

        if (big == 0) {
          for (var l = 0; l < bigarr[1].sh_options.length; l++) {
            var codeago = bigarr[big].selectattrid + '_' + bigarr[1].sh_options[l].sh_option_id
            for (var m = 0; m < this.data.goodsinfo.sh_childs.length; m++) {
              var codelast = this.data.goodsinfo.sh_childs[m].sh_sku_code;
              if (codeago == codelast) {
                if (that.data.buymode == "originbuy") {
                  bigarr[1].sh_options[l].num = this.data.goodsinfo.sh_childs[m].sh_no_promotion_stock;
                } else {
                  bigarr[1].sh_options[l].num = this.data.goodsinfo.sh_childs[m].sh_stock;
                }
              }
            }
          }
          for (var a = 0; a < bigarr.length; a++) {
            for (var b = 0; b < bigarr[a].sh_options.length; b++) {
              if (bigarr[a].sh_options[b].active == true) {
                numflag = true
                break
              }
            }
          }
          if (!numflag) {
            for (var a = 0; a < bigarr.length; a++) {
              for (var b = 0; b < bigarr[a].sh_options.length; b++) {
                bigarr[a].sh_options[b].num = 1
              }
            }
          }
          this.setData({
            selectimgindex: small
          })
        } else if (big == 1) {
          for (var n = 0; n < bigarr[0].sh_options.length; n++) {
            var codeago = bigarr[0].sh_options[n].sh_option_id + '_' + bigarr[big].selectattrid
            for (var o = 0; o < this.data.goodsinfo.sh_childs.length; o++) {
              var codelast = this.data.goodsinfo.sh_childs[o].sh_sku_code;
              if (codeago == codelast) {
                if (that.data.buymode == "originbuy") {
                  bigarr[0].sh_options[n].num = this.data.goodsinfo.sh_childs[o].sh_no_promotion_stock;
                } else {
                  bigarr[0].sh_options[n].num = this.data.goodsinfo.sh_childs[o].sh_stock;
                }
              }
            }
          }
          for (var a = 0; a < bigarr.length; a++) {
            for (var b = 0; b < bigarr[a].sh_options.length; b++) {
              if (bigarr[a].sh_options[b].active == true) {
                numflag = true
                break
              }
            }
          }
          if (!numflag) {
            for (var a = 0; a < bigarr.length; a++) {
              for (var b = 0; b < bigarr[a].sh_options.length; b++) {
                bigarr[a].sh_options[b].num = 1
              }
            }
          }
        }
        if (activeitem.sh_options[small].sh_image) {
          this.setData({
            thumbnail: activeitem.sh_options[small].sh_image
          })
        }
      } else if (activeitem.sh_options[small].active == true) { //如果属性选中
        activeitem.sh_options[small].active = false
        bigarr[big].selectattr = ''
        bigarr[big].selectattrid = ''
        this.setData({
          priceflag: true
        })
        if (that.data.buymode == "originbuy") {
          this.data.selectattrmoney = this.data.goodsinfo.sh_no_promotion_show_price
        } else {
          this.data.selectattrmoney = this.data.goodsinfo.sh_show_price
        }
        if (big == 0) {
          for (var b = 0; b < bigarr[0].sh_options.length; b++) {
            if (bigarr[0].sh_options[b].active == true) {
              numflag = true
              break
            }
          }
          if (!numflag) {
            for (var b = 0; b < bigarr[1].sh_options.length; b++) {
              bigarr[1].sh_options[b].num = 1
            }
            if (that.data.buymode == "originbuy") {
              this.data.goodsinfo.selectattrstock = this.data.goodsinfo.sh_no_promotion_all_stock
              this.data.goodsinfo.selectattrcommission = this.data.goodsinfo.sh_no_promotion_partner_commission
            } else {
              this.data.goodsinfo.selectattrstock = this.data.goodsinfo.sh_all_stock
              this.data.goodsinfo.selectattrcommission = this.data.goodsinfo.sh_partner_commission
            }
          }
        } else if (big == 1) {
          for (var b = 0; b < bigarr[1].sh_options.length; b++) {
            if (bigarr[1].sh_options[b].active == true) {
              numflag = true
              break
            }
          }
          if (!numflag) {
            for (var b = 0; b < bigarr[0].sh_options.length; b++) {
              bigarr[0].sh_options[b].num = 1
            }
            if (that.data.buymode == "originbuy") {
              this.data.goodsinfo.selectattrstock = this.data.goodsinfo.sh_no_promotion_all_stock
              this.data.goodsinfo.selectattrcommission = this.data.goodsinfo.sh_no_promotion_partner_commission
            } else {
              this.data.goodsinfo.selectattrstock = this.data.goodsinfo.sh_all_stock
              this.data.goodsinfo.selectattrcommission = this.data.goodsinfo.sh_partner_commission
            }
          }
        }
      }
    } else if (e.currentTarget.dataset.num > 0 && bigarr.length == 1 && e.currentTarget.dataset.skustock > 0) {
      if (activeitem.sh_options[small].active == false) {
        for (var i = 0; i < bigarr[big].sh_options.length; i++) {
          activeitem.sh_options[i].active = false
        }
        activeitem.sh_options[small].active = true
        bigarr[big].selectattr = activeitem.sh_options[small].sh_alias_name
        bigarr[big].selectattrid = activeitem.sh_options[small].sh_option_id
        this.setData({
          thumbnail: activeitem.sh_options[small].sh_image || this.data.goodsinfo.sh_galleries[0],
          selectimgindex: small
        })
      } else if (activeitem.sh_options[small].active == true) { //如果属性选中
        activeitem.sh_options[small].active = false
        bigarr[big].selectattr = ''
        bigarr[big].selectattrid = ''
        this.setData({
          priceflag: true,
          thumbnail: this.data.goodsinfo.sh_galleries[0]
        })
        if (that.data.buymode == "originbuy") {
          this.data.selectattrmoney = this.data.goodsinfo.sh_no_promotion_show_price
        } else {
          this.data.selectattrmoney = this.data.goodsinfo.sh_show_price
        }
      }
    }

    if (bigarr.length > 1) {
      for (var k = 0; k < this.data.goodsinfo.sh_childs.length; k++) {
        var code = this.data.goodsinfo.sh_childs[k].sh_sku_code
        if (code == bigarr[0].selectattrid + '_' + bigarr[1].selectattrid) {
          if (this.data.buymode == "originbuy") {
            this.data.goodsinfo.selectattrstock = this.data.goodsinfo.sh_childs[k].sh_no_promotion_stock;
            this.data.selectattrmoney = this.data.goodsinfo.sh_childs[k].sh_no_promotion_show_price;
            this.data.goodsinfo.selectattrcommission = this.data.goodsinfo.sh_childs[k].sh_no_promotion_partner_commission;
          } else {
            this.data.goodsinfo.selectattrstock = this.data.goodsinfo.sh_childs[k].sh_stock;
            this.data.selectattrmoney = this.data.goodsinfo.sh_childs[k].sh_show_price
            this.data.goodsinfo.selectattrcommission = this.data.goodsinfo.sh_childs[k].sh_partner_commission;
          }
          this.data.goodsinfo.selectattrallid = this.data.goodsinfo.sh_childs[k].sh_id
          this.setData({
            priceflag: false
          })
        }
      }
      if (this.data.goodsinfo.selectattrstock > 0) {
        if (this.data.selectnum > this.data.goodsinfo.selectattrstock) {
          this.setData({
            selectnum: 1,
            minutesimg: ''
          })
        }
        this.setData({
          minutesimg: '',
          plusimg: '3'
        })
      }
    } else {
      for (var k = 0; k < this.data.goodsinfo.sh_childs.length; k++) {
        var code = this.data.goodsinfo.sh_childs[k].sh_sku_code
        if (code == bigarr[0].selectattrid) {
          if (this.data.buymode == "originbuy") {
            this.data.goodsinfo.selectattrstock = this.data.goodsinfo.sh_childs[k].sh_no_promotion_stock;
            this.data.selectattrmoney = this.data.goodsinfo.sh_childs[k].sh_no_promotion_show_price;
            this.data.goodsinfo.selectattrcommission = this.data.goodsinfo.sh_childs[k].sh_no_promotion_partner_commission;
          } else {
            this.data.goodsinfo.selectattrstock = this.data.goodsinfo.sh_childs[k].sh_stock;
            this.data.selectattrmoney = this.data.goodsinfo.sh_childs[k].sh_show_price;
            this.data.goodsinfo.selectattrcommission = this.data.goodsinfo.sh_childs[k].sh_partner_commission;
          }
          this.data.goodsinfo.selectattrallid = this.data.goodsinfo.sh_childs[k].sh_id
          this.setData({
            priceflag: false
          })
        }
      }
      if (this.data.goodsinfo.selectattrstock > 0) {
        if (this.data.selectnum > this.data.goodsinfo.selectattrstock) {
          this.setData({
            selectnum: 1
          })
        }
        this.setData({
          minutesimg: '',
          plusimg: '3'
        })
      }
    }
    this.setData({
      selectattrmoney: this.data.selectattrmoney,
      goodsinfo: this.data.goodsinfo
    })
    // console.log(this.data.goodsinfo)
  },
  checkselectsku: function() {
    var that = this
    var bigarr = that.data.goodsinfo.sh_attributes
    if (bigarr.length > 1) {
      bigarr[0].sh_options.forEach(function(el, index) {
        if (el.active == true) { //第一个sku被选中,检查其他sku选中状态
          bigarr[1].sh_options.forEach(function(ele, index) {
            var codeago = el.sh_option_id + '_' + ele.sh_option_id
            that.data.goodsinfo.sh_childs.forEach(function(ela, index) {
              var codelast = ela.sh_sku_code;
              if (codeago == codelast) {
                if (that.data.buymode == "originbuy") {
                  ele.num = ela.sh_no_promotion_stock
                  if (ela.sh_no_promotion_stock == 0 || ela.sh_no_promotion_stock == null) {
                    ele.num = 0
                    ele.active = false
                  }
                  if (ele.active) {
                    that.data.selectattrmoney = ela.sh_no_promotion_show_price
                    that.data.goodsinfo.selectattrstock = ela.sh_no_promotion_stock
                    that.data.goodsinfo.selectattrcommission = ela.sh_no_promotion_partner_commission
                  } else {
                    that.data.selectattrmoney = that.data.goodsinfo.sh_no_promotion_show_price
                    that.data.goodsinfo.selectattrstock = that.data.goodsinfo.sh_no_promotion_all_stock
                    that.data.goodsinfo.selectattrcommission = that.data.goodsinfo.sh_no_promotion_partner_commission
                  }
                } else {
                  ele.num = ela.sh_stock;
                  if (ela.sh_stock == 0 || ela.sh_stock == null) {
                    ele.num = 0
                    ele.active = false
                  }
                  if (ele.active) {
                    that.data.selectattrmoney = ela.sh_show_price
                    that.data.goodsinfo.selectattrstock = ela.sh_stock
                    that.data.goodsinfo.selectattrcommission = ela.sh_partner_commission
                  } else {
                    that.data.selectattrmoney = that.data.goodsinfo.sh_no_promotion_show_price
                    that.data.goodsinfo.selectattrstock = that.data.goodsinfo.sh_no_promotion_all_stock
                    that.data.goodsinfo.selectattrcommission = that.data.goodsinfo.sh_no_promotion_partner_commission
                  }
                }
              }
            })
          })
        }
      })
      this.setData({
        selectattrmoney: this.data.selectattrmoney,
        goodsinfo: this.data.goodsinfo
      })
      bigarr[1].sh_options.forEach(function(el, index) {
        if (el.active == true) { //第二个sku被选中,检查其他sku选中状态
          bigarr[0].sh_options.forEach(function(ele, index) {
            var codeago = ele.sh_option_id + '_' + el.sh_option_id
            that.data.goodsinfo.sh_childs.forEach(function(ela, index) {
              var codelast = ela.sh_sku_code;
              if (codeago == codelast) {
                if (that.data.buymode == "originbuy") {
                  ele.num = ela.sh_no_promotion_stock;
                  if (ela.sh_no_promotion_stock == 0 || ela.sh_no_promotion_stock == null) {
                    ele.num = 0
                    ele.active = false
                  }
                  if (ele.active) {
                    that.data.selectattrmoney = ela.sh_no_promotion_show_price
                    that.data.goodsinfo.selectattrstock = ela.sh_no_promotion_stock
                    that.data.goodsinfo.selectattrcommission = ela.sh_no_promotion_partner_commission
                  }
                } else {
                  ele.num = ela.sh_stock;
                  if (ela.sh_stock == 0 || ela.sh_stock == null) {
                    ele.num = 0
                    ele.active = false
                  }
                  if (ele.active) {
                    that.data.selectattrmoney = ela.sh_show_price
                    that.data.goodsinfo.selectattrstock = ela.sh_stock
                    that.data.goodsinfo.selectattrcommission = ela.sh_partner_commission
                  }
                }
              }
            })
          })
        }
      })
      if (!bigarr[0].selectattr && !bigarr[0].selectattr) {
        if (that.data.buymode == "originbuy") {
          that.data.selectattrmoney = that.data.goodsinfo.sh_no_promotion_show_price
          that.data.goodsinfo.selectattrstock = that.data.goodsinfo.sh_no_promotion_all_stock
          that.data.goodsinfo.selectattrcommission = that.data.goodsinfo.sh_no_promotion_partner_commission
        } else {
          that.data.selectattrmoney = that.data.goodsinfo.sh_show_price
          that.data.goodsinfo.selectattrstock = that.data.goodsinfo.sh_all_stock
          that.data.goodsinfo.selectattrcommission = that.data.goodsinfo.sh_partner_commission
        }
      }
      this.setData({
        selectattrmoney: this.data.selectattrmoney,
        goodsinfo: this.data.goodsinfo
      })
    } else if (bigarr.length == 1) {
      bigarr[0].sh_options.forEach(function(el, index) {
        if (el.active == true) { //第一个sku被选中,检查其他sku选中状态
          var codeago = el.sh_option_id
          that.data.goodsinfo.sh_childs.forEach(function(ela, index) {
            var codelast = ela.sh_sku_code;
            if (codeago == codelast) {
              if (that.data.buymode == "originbuy") {
                el.num = ela.sh_no_promotion_stock
                if (ela.sh_no_promotion_stock == 0 || ela.sh_no_promotion_stock == null) {
                  el.num = 0
                  el.active = false
                }
                if (el.active) {
                  that.data.selectattrmoney = ela.sh_no_promotion_show_price
                  that.data.goodsinfo.selectattrstock = ela.sh_no_promotion_stock
                  that.data.goodsinfo.selectattrcommission = ela.sh_no_promotion_partner_commission
                } else {
                  that.data.selectattrmoney = that.data.goodsinfo.sh_no_promotion_show_price
                  that.data.goodsinfo.selectattrstock = that.data.goodsinfo.sh_no_promotion_all_stock
                  that.data.goodsinfo.selectattrcommission = that.data.goodsinfo.sh_no_promotion_partner_commission
                }
              } else {
                el.num = ela.sh_stock;
                if (el.sh_stock == 0 || ela.sh_stock == null) {
                  el.num = 0
                  el.active = false
                }
                if (el.active) {
                  that.data.selectattrmoney = ela.sh_show_price
                  that.data.goodsinfo.selectattrstock = ela.sh_stock
                  that.data.goodsinfo.selectattrcommission = ela.sh_partner_commission
                } else {
                  that.data.selectattrmoney = that.data.goodsinfo.sh_no_promotion_show_price
                  that.data.goodsinfo.selectattrstock = that.data.goodsinfo.sh_all_stock
                  that.data.goodsinfo.selectattrcommission = that.data.goodsinfo.sh_no_promotion_partner_commission
                }
              }
            }
          })
        }
      })
      this.setData({
        selectattrmoney: this.data.selectattrmoney,
        goodsinfo: this.data.goodsinfo
      })
    }
  },
  setdisabled: function() {
    var nowarr1 = [],
      flag1 = false,
      nowarr2 = [],
      flag2 = false,
      bigarr = this.data.goodsinfo.sh_attributes;
    if (bigarr.length == 1) {
      if (this.data.buymode == "originbuy") {
        for (var j = 0; j < bigarr[0].sh_options.length; j++) {
          num3 = 0
          for (var k = 0; k < this.data.goodsinfo.sh_childs.length; k++) {
            var code = this.data.goodsinfo.sh_childs[k].sh_sku_code
            if (code == bigarr[0].sh_options[j].sh_option_id) {
              num3 = num3 + this.data.goodsinfo.sh_childs[k].sh_no_promotion_stock
            }
          }
          bigarr[0].sh_options[j].skustock = num3
          if (num3 > 0) {
            nowarr1.push(bigarr[0].sh_options[j])
          }
        }
        if (nowarr1.length > 0) {
          nowarr1.forEach(function(el, index) {
            if (el.active) {
              flag1 = true;
            }
          })
          if (nowarr1[0].skustock > 0 && !flag1) {
            nowarr1[0].active = true
            bigarr[0].selectattrid = nowarr1[0].sh_option_id
            bigarr[0].selectattr = nowarr1[0].sh_alias_name
            for (var l = 0; l < this.data.goodsinfo.sh_childs.length; l++) {
              var code = this.data.goodsinfo.sh_childs[l].sh_sku_code
              if (code == nowarr1[0].sh_option_id) {
                this.data.selectattrmoney = this.data.goodsinfo.sh_childs[l].sh_show_price
                this.data.goodsinfo.selectattrallid = this.data.goodsinfo.sh_childs[l].sh_id
                this.data.goodsinfo.selectattrstock = this.data.goodsinfo.sh_childs[l].sh_no_promotion_stock;
                this.data.goodsinfo.selectattrcommission = this.data.goodsinfo.sh_childs[l].sh_partner_commission;
              }
            }
            this.setData({
              thumbnail: nowarr1[0].sh_image || this.data.goodsinfo.sh_galleries[0],
              goodsinfo: this.data.goodsinfo,
              selectattrmoney: this.data.selectattrmoney
            })
          }
        }
      } else {
        for (var j = 0; j < bigarr[0].sh_options.length; j++) {
          num4 = 0
          for (var k = 0; k < this.data.goodsinfo.sh_childs.length; k++) {
            var code = this.data.goodsinfo.sh_childs[k].sh_sku_code
            if (code == bigarr[0].sh_options[j].sh_option_id) {
              num4 = num4 + this.data.goodsinfo.sh_childs[k].sh_stock
            }
          }
          bigarr[0].sh_options[j].skustock = num4
          if (num4 > 0) {
            nowarr2.push(bigarr[0].sh_options[j])
          }
        }
        if (nowarr2.length > 0) {
          nowarr2.forEach(function(el, index) {
            if (el.active) {
              flag2 = true;
            }
          })
          if (nowarr2[0].skustock > 0 && !flag2) {
            nowarr2[0].active = true
            bigarr[0].selectattrid = nowarr2[0].sh_option_id
            bigarr[0].selectattr = nowarr2[0].sh_alias_name
            for (var l = 0; l < this.data.goodsinfo.sh_childs.length; l++) {
              var code = this.data.goodsinfo.sh_childs[l].sh_sku_code
              if (code == nowarr2[0].sh_option_id) {
                this.data.selectattrmoney = this.data.goodsinfo.sh_childs[l].sh_show_price
                this.data.goodsinfo.selectattrallid = this.data.goodsinfo.sh_childs[l].sh_id
                this.data.goodsinfo.selectattrstock = this.data.goodsinfo.sh_childs[l].sh_stock;
                this.data.goodsinfo.selectattrcommission = this.data.goodsinfo.sh_childs[l].sh_partner_commission;
              }
            }
            this.setData({
              thumbnail: nowarr2[0].sh_image || this.data.goodsinfo.sh_galleries[0],
              goodsinfo: this.data.goodsinfo,
              selectattrmoney: this.data.selectattrmoney
            })
          }
        }
      }
      this.setData({
        priceflag: false
      })
    } else if (bigarr.length > 1) {
      if (this.data.buymode == "originbuy") {
        for (var i = 0; i < bigarr.length; i++) {
          for (var j = 0; j < bigarr[i].sh_options.length; j++) {
            num3 = 0
            for (var k = 0; k < this.data.goodsinfo.sh_childs.length; k++) {
              var code = this.data.goodsinfo.sh_childs[k].sh_sku_code.split('_')
              if (code[0] == bigarr[i].sh_options[j].sh_option_id || code[1] == bigarr[i].sh_options[j].sh_option_id) {
                num3 = num3 + this.data.goodsinfo.sh_childs[k].sh_no_promotion_stock
              }
            }
            bigarr[i].sh_options[j].skustock = num3
          }
        }
      } else {
        for (var i = 0; i < bigarr.length; i++) {
          for (var j = 0; j < bigarr[i].sh_options.length; j++) {
            num4 = 0
            for (var k = 0; k < this.data.goodsinfo.sh_childs.length; k++) {
              var code = this.data.goodsinfo.sh_childs[k].sh_sku_code.split('_')
              if (code[0] == bigarr[i].sh_options[j].sh_option_id || code[1] == bigarr[i].sh_options[j].sh_option_id) {
                num4 = num4 + this.data.goodsinfo.sh_childs[k].sh_stock
              }
            }
            bigarr[i].sh_options[j].skustock = num4
          }
        }
      }
    }
    if (this.data.buymode == "originbuy") {
      if (this.data.goodsinfo.sh_no_promotion_all_stock == 0) {
        this.setData({
          plusimg: '',
          inhibitInput: 'disabled'
        })
      } else {
        this.setData({
          plusimg: '3',
          inhibitInput: ''
        })
      }
    } else {
      if (this.data.goodsinfo.sh_all_stock == 0) {
        this.setData({
          plusimg: '',
          inhibitInput: 'disabled'
        })
      } else {
        this.setData({
          plusimg: '3',
          inhibitInput: ''
        })
      }
    }

    this.setData({
      goodsinfo: this.data.goodsinfo
    })
    // console.log(this.data.goodsinfo)
  },
  btnminutes: function() {
    if (this.data.inhibitInput == '') {
      if (this.data.selectnum > 1) {
        this.setData({
          selectnum: Number(this.data.selectnum) - 1
        })
        if (this.data.selectnum == 1) {
          this.setData({
            minutesimg: ''
          })
        }
      } else {
        this.setData({
          minutesimg: ''
        })
        shihan.showToast.call(this, '亲，请至少购买一件哦');
      }
      if (this.data.selectnum < this.data.goodsinfo.selectattrstock) {
        this.setData({
          plusimg: '3'
        })
      }
    }
  },
  btnplus: function() {
    if (this.data.inhibitInput == '') {
      if (this.data.selectnum < this.data.goodsinfo.selectattrstock) {
        this.setData({
          selectnum: Number(this.data.selectnum) + 1
        })
      } else {
        this.setData({
          plusimg: ''
        })
        shihan.showToast.call(this, '库存已达到上限');
      }
      if (this.data.selectnum > 1) {
        this.setData({
          minutesimg: '3',
        })
      }
    }
  },
  shopnumber: function(e) {
    if (e.detail.value <= 1) {
      this.setData({
        selectnum: 1,
        minutesimg: ''
      })
    } else if (e.detail.value >= this.data.goodsinfo.selectattrstock) {
      this.setData({
        selectnum: this.data.goodsinfo.selectattrstock,
        plusimg: '',
      })
    } else {
      this.setData({
        selectnum: Number(e.detail.value)
      })
    }

    if (this.data.selectnum > 1) {
      this.setData({
        minutesimg: '3'
      })
    }
    if (this.data.selectnum < this.data.goodsinfo.selectattrstock) {
      this.setData({
        plusimg: '3',
      })
    }
  },
  addcollection: function(e) {
    var that = this
    token = wx.getStorageSync('token');
    var collecid = e.currentTarget.dataset.id;
    if (token) {
      if (this.data.collectionflag == false) {
        shihan.sendRequest(config.add_favorite, 'POST', {
            id: collecid,
            type: 1
          })
          .then(function(response) {
            console.log(response);
            if (response.data.code == 0 || response.data.code == 1103) {
              that.data.goodsinfo.sh_is_favorite = 1
              that.setData({
                collectionflag: true,
                goodsinfo: that.data.goodsinfo
              })
              shihan.showToast.call(that, '添加收藏成功');
            } else if (response.data.code == 1101) { //用户未登录
              app.commonNoLogin()
            } else {
              shihan.showToast.call(that, response.data.msg);
            }
          }, function(error) {
            console.log(error);
          });
      } else {
        shihan.sendRequest(config.remove_favorite, 'POST', {
            id: collecid,
            type: 1
          })
          .then(function(response) {
            // console.log(response);
            if (response.data.code == 0) {
              that.data.goodsinfo.sh_is_favorite = 0;
              that.setData({
                collectionflag: false,
                goodsinfo: that.data.goodsinfo
              })
              shihan.showToast.call(that, '取消收藏成功');
            }
          }, function(error) {
            console.log(error);
          });
      }
    } else {
      app.commonNoLogin()
    }
  }, //add_favorite
  addextension: function(e) {
    var that = this
    token = wx.getStorageSync('token');
    var collecid = e.currentTarget.dataset.id;
    if (token) {
      if (this.data.goodsinfo.sh_partner_favorite == 0) {
        shihan.sendRequest(config.add_extension, 'POST', {
            product_id: collecid
          })
          .then(function(response) {
            console.log(response);
            if (response.data.code == 0) {
              that.data.goodsinfo.sh_partner_favorite = 1
              that.setData({
                goodsinfo: that.data.goodsinfo
              })
              shihan.showToast.call(that, '加入推广清单成功');
            } else {
              shihan.showToast.call(that, response.data.msg);
            }
          }, function(error) {
            console.log(error);
          });
      } else {
        shihan.sendRequest(config.add_extension, 'POST', {
            product_id: collecid
          })
          .then(function(response) {
            console.log(response);
            if (response.data.code == 0) {
              that.data.goodsinfo.sh_partner_favorite = 0
              that.setData({
                goodsinfo: that.data.goodsinfo
              })
              shihan.showToast.call(that, '删除推广清单成功');
            }
          }, function(error) {
            console.log(error);
          });
      }
    } else {
      app.commonNoLogin()
    }
  },
  copypartnernum: function() {
    var that = this
    wx.setClipboardData({
      data: new String(that.data.goodsinfo.sh_remind_no_partner_arr.sh_wechat_num),
      success: function(res) {
        wx.getClipboardData({
          success: function(res) {
            console.log(res.data)
          }
        })
      }
    })
  },
  copycategorynum: function() {
    var that = this
    wx.showModal({
      title: '提示',
      content: that.data.goodsinfo.sh_remind_category_arr.sh_content,
      confirmText: "我知道了",
      confirmColor: "#c40000",
      showCancel: false,
      success: function(res) {
        if (res.confirm) {
          wx.setClipboardData({
            data: String(that.data.goodsinfo.sh_remind_category_arr.sh_wechat_num),
            success: function(res) {
              wx.getClipboardData({
                success: function(res) {
                  console.log(res.data)
                }
              })
            }
          })
        }
      }
    })
  },
  openstoredetail: function(e) { //e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/storedetail/storedetail?id=' + e.currentTarget.dataset.id + '&type=' + e.currentTarget.dataset.type
    })
  },
  viewgoodsDetail: function(e) {
    wx.navigateTo({
      url: '/pages/goodsdetail/goodsdetail?goodsid=' + e.currentTarget.dataset.id
    })
  },
  looklicense: function(e) {
    wx.navigateTo({
      url: '/pages/other/licensedetail/licensedetail?sub=' + JSON.stringify(e.currentTarget.dataset.sub)
    })
  },
  openfold: function() {
    if (this.data.foldflag == false) {
      this.setData({
        foldflag: true
      })
    } else {
      this.setData({
        foldflag: false
      })
    }
  },
  lookreview: function(e) {
    wx.navigateTo({
      url: '/pages/other/allreview/allreview?id=' + e.currentTarget.dataset.id
    })
  },
  previewImg: function(e) {
    var imgidx = e.currentTarget.dataset.imgidx,
      imgs = this.data.goodsinfo.sh_galleries;
    wx.previewImage({
      current: imgs[imgidx],
      urls: imgs
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    clearInterval(goodstimer);
    clearInterval(goodstimer2);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearInterval(goodstimer);
    clearInterval(goodstimer2);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(options) {
    var that = this,
      shareurl, sharetit;
    console.log(options)
    sharetit = that.data.goodsinfo.sh_name
    var customerId = wx.getStorageSync('customerId');
    if (options.target) {
      if (options.target.dataset.sharetype == 'goods') {
        if (options.target.dataset.id) {
          shareurl = '/pages/goodsdetail/goodsdetail?goodsid=' + that.data.goodsid + '&cid=' + options.target.dataset.id
        } else {
          shareurl = '/pages/goodsdetail/goodsdetail?goodsid=' + that.data.goodsid + '&pid=' + customerId
        }
      } else {
        sharetit = '【帮我拼一单】' + that.data.goodsinfo.sh_name
        shareurl = '/pages/other/teamdetail/teamdetail?teamid=' + that.data.shareteamid + '&pid=' + customerId
      }
    } else {
      shareurl = '/pages/goodsdetail/goodsdetail?goodsid=' + that.data.goodsid + '&pid=' + customerId
    }
    return {
      title: sharetit,
      path: shareurl,
      imageUrl: that.data.goodsinfo.sh_galleries[0],
      success: function(res) {
        // 转发成功
        if (that.data.goodsinfo.sh_product_type == 1) {
          shihan.sendRequest(config.add_share_info, 'POST', {
              product_id: that.data.goodsid
            })
            .then(function(response) {
              // console.log(response.data);
            }, function(error) {
              console.log(error);
            });
        }
      },
      fail: function(res) {
        // 转发失败
      }
    }
  }
})